package com.sxkiler.demo.maintest.mongodb;

import com.mongodb.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;

import java.util.*;
import com.sxkiler.demo.model.*;

public class MongodbDemo {

    public static  MongoClient createMongoDatabase() {
        MongoClientOptions.Builder userdbBuilder = MongoClientOptions.builder();
        userdbBuilder.connectTimeout(6000);
        userdbBuilder.socketTimeout(6000);
        userdbBuilder.maxWaitTime(6000);
        userdbBuilder.connectionsPerHost(6000);
        userdbBuilder.readPreference(ReadPreference.secondaryPreferred());
        MongoClientOptions userdbOptions = userdbBuilder.build();

        MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(
                "kingdee",
                "ownercloud_alpha",
                "wojiayun2017".toCharArray());

        ServerAddress serverAddress = new ServerAddress("172.20.176.216", 27017);
        //创建mongodb的连接客户端，对于这个创建ibatis中也有此类用法
        return new MongoClient(
                serverAddress,
                mongoCredential,
                userdbOptions);
    }

    public static void main(String args[]){
        // 连接到 mongodb 服务
        MongoClient client = createMongoDatabase();
        MongoTemplate mongoTemplate = new MongoTemplate(client,"ownercloud_alpha");
        //根据mongodb数据库的名称获取mongodb对象 ,
        List<String> onumberSet=new ArrayList<String>();
        onumberSet.add("2020-04-13");
        onumberSet.add("2020-04-14");
        onumberSet.add("2020-04-15");
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("execDate").in(onumberSet)),
                Aggregation.match(Criteria.where("topic").is("ownercloud-alpha-topic")),
                Aggregation.group("topic").sum("execSpand").as("total")
        );

        AggregationResults<BasicDBObject> outputType=mongoTemplate.aggregate(agg,"mqMsgVo", BasicDBObject.class);
        for (Iterator<BasicDBObject> iterator = outputType.iterator(); iterator.hasNext();) {
            DBObject obj = iterator.next();
            System.out.println(((BasicDBObject) obj).get("total"));
        }
    }
}
